//
//  HongBaoViewController.m
//  SelfDriving
//
//  Created by apple on 16/3/4.
//  Copyright © 2016年 apple. All rights reserved.
//
//我的收益-红包及发款记录
#import "HongBaoViewController.h"
#import "hongbaoCell.h"
#import "BusinessService+WD.h"
#import "UIChooseTableView.h"
@interface HongBaoViewController ()<UITableViewDataSource,UITableViewDelegate,UIChooseTableViewDelegate,UIDatePickerViewDelegate,BaseTableDetelage>
@property (weak, nonatomic) IBOutlet UIButton *typeBtn;
@property (weak, nonatomic) IBOutlet BaseTable *table;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;

@end

@implementation HongBaoViewController{
    UIChooseTableView *chooseTabel;
    NSString *type;//发出红包，收到红包，发款记录
    NSMutableArray *data;
    NSString *years;
    
    NSString *stime;
    NSString *etime;
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    int year = (int)[dateComponent year];
    
    type = @"收到的红包";
    years = [NSString stringWithFormat:@"%d",year];
    _table.bdelegate = self;
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *date =  [dateFormatter stringFromDate:today];
    stime = date;
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:today];//前一天
    NSString *eate =  [dateFormatter stringFromDate:lastDay];
    etime = eate;
   CGSize  s = [ValidateHelper sizeOfText:_typeBtn.titleLabel.text theFont:[UIFont systemFontOfSize:17]];
    _typeBtn.imageEdgeInsets = UIEdgeInsetsMake(0,_typeBtn.frame.size.width - s.width + 30, 0, 0);
    
    //xhw2018-1-16改bug15069:
    [self initData:1];
    
}
-(void)initData:(int)index{
    if ([type isEqualToString:@"发款记录"]) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//        [dic setObject:[NSNumber numberWithInteger:[ValidateHelper cTimestampFromString:[NSString stringWithFormat:@"%@ 0:0:0",stime] format:@"yyyy-MM-dd HH:mm:ss"]] forKey:@"endtime"];
//        [dic setObject:[NSNumber numberWithInteger:[ValidateHelper cTimestampFromString:[NSString stringWithFormat:@"%@ 0:0:0",etime] format:@"yyyy-MM-dd HH:mm:ss"]] forKey:@"starttime"];
        [dic setObject:[NSNumber numberWithInteger:[ValidateHelper cTimestampFromString:[NSString stringWithFormat:@"%@ 0:0:0",stime] format:@"yyyy-MM-dd HH:mm:ss"]] forKey:@"starttime"];
        [dic setObject:[NSNumber numberWithInteger:[ValidateHelper cTimestampFromString:[NSString stringWithFormat:@"%@ 0:0:0",etime] format:@"yyyy-MM-dd HH:mm:ss"]] forKey:@"endtime"];
        [[BusinessService shareInstance]consume_list:dic success:^(id result) {
            data = result;
            [_table reloadData];
        } failure:^(id result) {
            [SVProgressHUD showErrorWithStatus:result];
        }];
    }else{
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        years = [years stringByReplacingOccurrencesOfString:@"年" withString:@""];
        [dic setObject:years forKey:@"year"];
        [dic setObject:type forKey:@"type"];
        [dic setObject:[NSNumber numberWithInt:index] forKey:@"page"];
        [[BusinessService shareInstance]shoudao_or_fachu:dic success:^(id result) {
            data = result;
            [_table reloadData];
        } failure:^(id result) {
            [SVProgressHUD showErrorWithStatus:result];
        }];
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (![type isEqualToString:@"发款记录"]) {
        return data.count==0?0:2;
    }
    return data.count==0?1:2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    if ([type isEqualToString:@"发款记录"]) {
        return data.count;
    }else{
        LoginResponseModel *model = [data lastObject];
        return  model.list.count;
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([type isEqualToString:@"发款记录"]) {
        return 8;
    }
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 8;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([type isEqualToString:@"发款记录"]) {
        if (indexPath.section == 0) {
            return 170;
        }
    }else{
        if (indexPath.section == 0) {
            return 277;
        }
    }
    return 50;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([type isEqualToString:@"发款记录"]) {
        if (indexPath.section == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
            cell.backgroundColor = colorBG;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            UIButton *btn = (UIButton *)[cell viewWithTag:10];
            btn.layer.cornerRadius = 4;
            [btn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
            UILabel *label = (UILabel *)[self.view viewWithTag:40];
            UILabel *elabel = (UILabel *)[self.view viewWithTag:41];
            if (label.text.length==0) {
                label.text = etime;
            }
            if (elabel.text.length==0) {
                elabel.text = stime;
            }
            return cell;
        }
        LoginResponseModel *model = [data objectAtIndex:indexPath.row];
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        UILabel *name =[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 200, 30)];
        name.font = [UIFont systemFontOfSize:15];
        name.text = model.title;
        [cell.contentView addSubview:name];
        
        UILabel *time =[[UILabel alloc]initWithFrame:CGRectMake(10, 20, 200, 30)];
        time.font = [UIFont systemFontOfSize:14];
        time.text = [ValidateHelper doubleConvertDate:[model.createtime doubleValue] FormatterStr:@"MM-dd"];
        time.textColor = [UIColor grayColor];
        [cell.contentView addSubview:time];
        if ([model.type intValue]==1) {//收入
//            cell.detailTextLabel.text = [NSString stringWithFormat:@"+%@元",[ValidateHelper numberFormat:model.money]];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@元",model.money];
            cell.detailTextLabel.textColor = [UIColor redColor];
        }else{//支出
//            cell.detailTextLabel.text = [NSString stringWithFormat:@"-%@元",[ValidateHelper numberFormat:model.money]];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@元",model.money];
            cell.detailTextLabel.textColor = [UIColor greenColor];
        }
        return  cell;
        
        
    }else if ([type isEqualToString:@"收到的红包"]){
        
        LoginResponseModel *model = [data lastObject];
        if (indexPath.section == 0) {
            hongbaoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hongbaoCell"];
            
            NSDate *now = [NSDate date];
            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
            NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
            int year = (int)[dateComponent year];
            UIButton *btn = (UIButton *)[cell viewWithTag:998];
            if (btn.titleLabel.text.length == 0) {
                [btn setTitle:[NSString stringWithFormat:@"%d年",year]  forState:UIControlStateNormal];
            }
            cell.head_img.layer.cornerRadius  = 30;
            cell.head_img.clipsToBounds = YES;
            cell.timeBtn.layer.cornerRadius = 10;
            CGSize  s = [ValidateHelper sizeOfText:cell.timeBtn.titleLabel.text theFont:[UIFont systemFontOfSize:17]];
            cell.timeBtn.imageEdgeInsets = UIEdgeInsetsMake(0,cell.timeBtn.frame.size.width - s.width + 35, 0, 0);

//            cell.timeBtn.imageEdgeInsets = UIEdgeInsetsMake(0, cell.timeBtn.frame.size.width-10, 0, 0);
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.nameLable.text = [NSString stringWithFormat:@"%@共收到",[AppDelegate shareDelegate].user.nickname];
            [cell.head_img sd_setImageWithURL:[NSURL URLWithString:[AppDelegate shareDelegate].user.headsmall] placeholderImage:[UIImage imageNamed:@"mrtx"]];
            cell.shoudaoLable.text =  [NSString stringWithFormat:@"%d",[model.total_num intValue]];
            cell.zuijiaLable.text =  [NSString stringWithFormat:@"%d",[model.best_num intValue]];
//            NSString *m = [ValidateHelper numberFormat:[NSString stringWithFormat:@"%f",model.total_money]];
            NSString *m = model.total_money;
            [ValidateHelper colorLable:cell.moneyLable str:[NSString stringWithFormat:@"%@元",m] key:@"元" color:[UIColor blackColor] size:14];
            cell.fachu.hidden = YES;
            return cell;
        }
        NSMutableDictionary *dic = [model.list objectAtIndex:indexPath.row];
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        UILabel *name =[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 200, 30)];
        name.font = [UIFont systemFontOfSize:15];
        name.text = [dic objectForKey:@"nickname"];
        [cell.contentView addSubview:name];
        
        UILabel *time =[[UILabel alloc]initWithFrame:CGRectMake(10, 20, 200, 30)];
        time.font = [UIFont systemFontOfSize:14];
        time.text = [ValidateHelper doubleConvertDate:[[dic objectForKey:@"createtime"] doubleValue] FormatterStr:@"MM-dd"];
        time.textColor = [UIColor grayColor];
        [cell.contentView addSubview:time];
//        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@元",[ValidateHelper numberFormat:[dic objectForKey:@"money"]]];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@元",[dic objectForKey:@"money"]];
        
        return cell;
    }else{//发出的红包
        LoginResponseModel *model = [data lastObject];
        if (indexPath.section == 0) {
            hongbaoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hongbaoCell"];
            
            NSDate *now = [NSDate date];
            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
            NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
            int year = (int)[dateComponent year];
            UIButton *btn = (UIButton *)[cell viewWithTag:998];
            if (btn.titleLabel.text.length == 0) {
                [btn setTitle:[NSString stringWithFormat:@"%d年",year]  forState:UIControlStateNormal];
            }
            cell.head_img.layer.cornerRadius  = 30;
            cell.head_img.clipsToBounds = YES;
            cell.timeBtn.layer.cornerRadius = 10;
//            cell.timeBtn.imageEdgeInsets = UIEdgeInsetsMake(0, cell.timeBtn.frame.size.width-10, 0, 0);
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.nameLable.text = [NSString stringWithFormat:@"%@共发出",[AppDelegate shareDelegate].user.nickname];
            [cell.head_img sd_setImageWithURL:[NSURL URLWithString:[AppDelegate shareDelegate].user.headsmall] placeholderImage:[UIImage imageNamed:@"mrtx"]];
            cell.shoudaoLable.hidden = YES;
            cell.zuijiaLable.hidden = YES;
            cell.title1.hidden = YES;
            cell.title2.hidden = YES;
            cell.fachu.hidden = NO;
            
            NSString *tmep = [NSString stringWithFormat:@"发出红包%d个",[model.total_num intValue]];
            [ValidateHelper colorLable:cell.fachu str:tmep key:[NSString stringWithFormat:@"%d",[model.total_num intValue]]];
            
//            NSString *m = [ValidateHelper numberFormat:[NSString stringWithFormat:@"%f",model.total_money]];
            NSString *m = model.total_money;

            [ValidateHelper colorLable:cell.moneyLable str:[NSString stringWithFormat:@"%@元",m] key:@"元" color:[UIColor blackColor] size:14];
            return cell;
        }
        NSMutableDictionary *dic = [model.list objectAtIndex:indexPath.row];
        UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        UILabel *name =[[UILabel alloc]initWithFrame:CGRectMake(10, 0, 200, 30)];
        name.font = [UIFont systemFontOfSize:15];
        name.text = [dic objectForKey:@"nickname"];
        [cell.contentView addSubview:name];
        
        UILabel *time =[[UILabel alloc]initWithFrame:CGRectMake(10, 20, 200, 30)];
        time.font = [UIFont systemFontOfSize:14];
        time.text = [ValidateHelper doubleConvertDate:[[dic objectForKey:@"createtime"] doubleValue] FormatterStr:@"MM-dd"];
        time.textColor = [UIColor grayColor];
        [cell.contentView addSubview:time];
//        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@元",[ValidateHelper numberFormat:[dic objectForKey:@"money"]]];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@元",[dic objectForKey:@"money"]];
        return cell;
        
        
    }
    return nil;
}
#pragma  mark 时间选择
- (IBAction)timeAction:(UIButton *)sender {
    NSMutableArray *tag_ary = [[NSMutableArray alloc]init];
    
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    int year = (int)[dateComponent year];
    for(int i=year-4;i<=year;i++){
        [tag_ary addObject:[[NSMutableDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:@"%d年",i],@"name",[NSString stringWithFormat:@"%d",i],@"id", nil]];
    }
    
    chooseTabel = [[UIChooseTableView alloc] initWithFrame:CGRectMake(0.0f, SCRE_HEIGHT, SCRE_WIDTH, 260.0f)];
    chooseTabel.delegate = self;
    chooseTabel.lanel_title.text = @"选择时间";
    
    chooseTabel.mainData  = tag_ary;
    [chooseTabel up];
    [[[[UIApplication sharedApplication] windows] firstObject] addSubview:chooseTabel];
}
-(void)didSelectDate:(UITableView *)chooseTableView indexPath:(NSIndexPath *)indexPath  string:(NSMutableDictionary *)string{
    if([chooseTabel.lanel_title.text isEqualToString:@"选择时间"]){
        UIButton *btn = (UIButton *)[self.view viewWithTag:998];
        [btn setTitle:[NSString stringWithFormat:@"%@",[string objectForKey:@"name"]] forState:UIControlStateNormal];
        years = [string objectForKey:@"name"];
        [_table Refresh];
    }else{
        [_typeBtn setTitle:[string objectForKey:@"name"] forState:UIControlStateNormal];
        type = [string objectForKey:@"name"];
        if ([type isEqualToString:@"发款记录"]) {
            
            [_table Refresh];
            
            
            
        }else{
            [_table Refresh];
        }
        CGSize  s = [ValidateHelper sizeOfText:_typeBtn.titleLabel.text theFont:[UIFont systemFontOfSize:17]];
        _typeBtn.imageEdgeInsets = UIEdgeInsetsMake(0,_typeBtn.frame.size.width - s.width + 30, 0, 0);

    }
}
#pragma  mark 红包类型
- (IBAction)hongTypeAction:(UIButton *)sender {
    NSMutableArray *tag_ary = [[NSMutableArray alloc]initWithObjects:
                               @{@"name":@"收到的红包",@"id":@"1"},
                               @{@"name":@"我发的红包",@"id":@"1"},
                               @{@"name":@"发款记录",@"id":@"1"}, nil];
    
    chooseTabel = [[UIChooseTableView alloc] initWithFrame:CGRectMake(0.0f, SCRE_HEIGHT, SCRE_WIDTH, 260.0f)];
    chooseTabel.delegate = self;
    chooseTabel.lanel_title.text = @"选择类型";
    chooseTabel.mainData  = tag_ary;
    [chooseTabel up];
    [[[[UIApplication sharedApplication] windows] firstObject] addSubview:chooseTabel];
}
#pragma  mark 时间选择
- (IBAction)timeActions:(UIButton *)sender {
    
    if (sender.tag == 20) {
        UIDatePickerView  *datePickerView = [[UIDatePickerView alloc] initWithFrame:CGRectMake(15, SCRE_HEIGHT, SCRE_WIDTH-30, 180)];
        datePickerView.backgroundColor = [UIColor whiteColor];
        datePickerView.delegate = self;
        datePickerView.lanel_title.text = @"开始时间";
        [datePickerView up];
        datePickerView.tag = sender.tag+10;
        [[[[UIApplication sharedApplication] windows] firstObject] addSubview:datePickerView];
        
    }else if (sender.tag == 21){
        UIDatePickerView  *datePickerView = [[UIDatePickerView alloc] initWithFrame:CGRectMake(15, SCRE_HEIGHT, SCRE_WIDTH-30, 180)];
        datePickerView.backgroundColor = [UIColor whiteColor];
        datePickerView.delegate = self;
        datePickerView.lanel_title.text = @"开始时间";
        [datePickerView up];
        datePickerView.tag = sender.tag+10;
        [[[[UIApplication sharedApplication] windows] firstObject] addSubview:datePickerView];
        
    }
}
- (void)didSelectDate:(UIDatePickerView *)pickerView Date:(NSMutableDictionary *)date
{
    if (pickerView.tag == 30) {
        UILabel *label = (UILabel *)[self.view viewWithTag:40];
        label.text = [date objectForKey:@"date"];
        stime = [date objectForKey:@"dates"];
    }else if (pickerView.tag == 31){
        UILabel *label = (UILabel *)[self.view viewWithTag:41];
        label.text = [date objectForKey:@"date"];
        etime = [date objectForKey:@"dates"];
    }
    pickerView.hidden = YES;
}
#pragma mark 查询
- (IBAction)selectAction:(UIButton *)sender {
    [_table Refresh];
}
- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
